package com.cardbaobao.cardbabyclient.ui.fragment.card;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.MemberInfo;
import com.cardbaobao.cardbabyclient.model.UserBindCards;
import com.cardbaobao.cardbabyclient.ui.activity.BankCardManageActivity;
import com.cardbaobao.cardbabyclient.ui.activity.BankCardVerifyActivity;
import com.cardbaobao.cardbabyclient.ui.activity.IdentifyVerifyActivity;
import com.cardbaobao.cardbabyclient.ui.activity.ReplaceCardActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.dialog.UnbindCardDialog;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.ui.helper.BankCardBgHelper;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/14 9:19.
 */

public class DebitCardFragment extends BaseFragment {
    private String prePageId;
    public void setBuriedData(String prePageId){
        this.prePageId=prePageId;
    }
    private static final int TYPE_ADD_CARD=1;//添加储蓄卡
    private static final int TYPE_REPLACE_CARD=2;//更换储蓄卡
    @BindView(R.id.ll_add_already)
    LinearLayout llAddAlready;//已添加储蓄卡展示的布局
    @BindView(R.id.ll_card_layout)
    LinearLayout llCardLayout;//已添加的储蓄卡布局
    @BindView(R.id.civ_logo)
    CircleImageView civLogo;
    @BindView(R.id.tv_bank)
    TextView tvBank;
    @BindView(R.id.tv_card)
    TextView tvCard;
    @BindView(R.id.ll_not_add)
    LinearLayout llNotAdd;//未添加储蓄卡时展示的布局
    @BindView(R.id.tv_add_card)
    TextView tvAddCard;

    UserBindCards.DebitCard card;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_debit_card;
    }

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {
        mCurrentPageId= Self.Page.app_debit_card_page;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.tv_unbind,R.id.tv_replace_card,R.id.ll_add_card})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_unbind:
                //解绑
                SelfUtils.buriedClickData(Self.Action.app_click_debit_card_unbind,
                        Self.Action.app_click_debit_card_unbind_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                showUnBindDialog(card.getDebit_card_name(),
                        card.getDebit_card_no());
                break;
            case R.id.tv_replace_card:
                //更换储蓄卡
                SelfUtils.buriedClickData(Self.Action.app_click_debit_card_replace,
                        Self.Action.app_click_debit_card_replace_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                loadRealNameInfo(TYPE_REPLACE_CARD);
                break;
            case R.id.ll_add_card:
                //添加储蓄卡
                SelfUtils.buriedClickData(Self.Action.app_click_debit_card_add,
                        Self.Action.app_click_debit_card_add_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                loadRealNameInfo(TYPE_ADD_CARD);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDebitCardSuccess(Event.BindDebitCardSuccess cardSuccess){
        Activity activity=getActivity();
        if(activity instanceof BankCardManageActivity){
            ((BankCardManageActivity)activity).loadData();
        }
    }

    //获取实名认证信息
    private void loadRealNameInfo(final int type){
        showProgressDialog(false);
        Api.getMemberInfo(mApplication.getUser().getID()).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        BaseResult result=JsonUtil.json2Object(s,BaseResult.class);
                        if(result.getCode()==Constant.SUC_CODE){
                            Object data=result.getData();
                            if(data instanceof JSONObject){
                                JSONObject json= (JSONObject) data;
                                MemberInfo info=JsonUtil.json2Object(json.getJSONObject("MemberInfo").toJSONString(),
                                        MemberInfo.class);
                                if(info!=null){
                                    String name=info.getTrueName();
                                    String idCardNo=info.getIDCardNo();
                                    if(TextUtils.isEmpty(name)||TextUtils.isEmpty(idCardNo)){
                                        //未实名认证
                                        Intent intent=new Intent();
                                        intent.setClass(mContext, IdentifyVerifyActivity.class);
                                        intent.putExtra(BankCardVerifyActivity.PAGE_FROM_I,
                                                BankCardVerifyActivity.ACTIVITY_CARD_MANAGE_ADD);
                                        intent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                                        startActivity(intent);
                                    }else{
                                        //已实名认证
                                        Intent intent=new Intent();
                                        intent.putExtra(IdentifyVerifyActivity.NAME_S,name);
                                        intent.putExtra(IdentifyVerifyActivity.ID_CARD_NO_S,idCardNo);
                                        if(type==TYPE_ADD_CARD){
                                            intent.setClass(mContext, IdentifyVerifyActivity.class);
                                            intent.putExtra(BankCardVerifyActivity.PAGE_FROM_I,
                                                    BankCardVerifyActivity.ACTIVITY_CARD_MANAGE_ADD);
                                        }else{
                                            intent.setClass(mContext, ReplaceCardActivity.class);
                                        }
                                        intent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                                        startActivity(intent);
                                    }
                                }else{
                                    ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                            getString(R.string.string_data_exception));
                                }
                            }
                        }else{
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    public void setData(List<UserBindCards.DebitCard> cards){
        if(cards!=null&&cards.size()>0){
            llAddAlready.setVisibility(View.VISIBLE);
            llNotAdd.setVisibility(View.GONE);
            card=cards.get(0);
            ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL+card.getPicture(),
                    civLogo,
                    R.mipmap.img_default_square);
            tvBank.setText(card.getDebit_card_name());
            String cardNumber=card.getDebit_card_no();
            StringBuilder sb=new StringBuilder(Constant.CARD_PREFIX);
            int length=cardNumber.length();
            for(int i=length-4;i<length;i++){
                sb.append(cardNumber.charAt(i));
            }
            tvCard.setText(sb.toString());
            llCardLayout.setBackgroundResource(
                    BankCardBgHelper.getBankCardBgRes(card.getBack_color()));
        }else{
            tvAddCard.setText("添加储蓄卡");
            llNotAdd.setVisibility(View.VISIBLE);
            llAddAlready.setVisibility(View.GONE);
        }
    }

    //解绑储蓄卡对话框
    private void showUnBindDialog(String cardName,final String debitCardNo){
        final UnbindCardDialog dialog=new UnbindCardDialog(getActivity(),
                "您正在解绑--"+
                        cardName+
                        "储蓄卡（"+debitCardNo.substring(debitCardNo.length()-4)+
                "）");
        dialog.setClickedListener(new UnbindCardDialog.ClickedListener() {
            @Override
            public void onEnsureClicked() {
                dialog.dismiss();
                unBindDebitCard(debitCardNo);
            }
        });
        dialog.show();
    }

    /**
     * 解绑储蓄卡
     * @param cardNumber
     */
    private void unBindDebitCard(String cardNumber){
        showProgressDialog(false);
        Api.unBindDebitCard(cardNumber,
                String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        BaseResult result= JsonUtil.json2Object(s,BaseResult.class);
                        if(result.getCode()== Constant.SUC_CODE){
                            //删除成功
                            ToastUtil.showToast("解绑成功");
                            setData(null);
                        }else{
                            //删除失败
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }
}
